package com.zoran.study.spring.controller.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * RequestLoggingFilter
 *
 * @author zouxm
 * @date 2018/6/22
 */
public class RequestLoggingFilter extends OncePerRequestFilter {
    private static final Logger LOGGER = LoggerFactory.getLogger(RequestLoggingFilter.class);

    public RequestLoggingFilter() {
    }

    @Override
    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String requestId = UUID.randomUUID().toString();
        request.setAttribute("com.fincloud.request.uuid", requestId);
        request.setAttribute("com.fincloud.request.arrival-time", Long.valueOf(System.currentTimeMillis()));
        LOGGER.info("[{}] {} {} from {}", new Object[]{requestId, request.getMethod(), request.getRequestURI(), request.getRemoteAddr()});
        filterChain.doFilter(request, response);
    }
}
